<?php
/**
 * 提现记录
 */

namespace app\api\model;


use app\common\model\Model;

use app\common\model\AdminNotify;
use think\Db;
class Withdraw extends  Model
{
    const TABLE_NAME = 'withdraw_record';
    const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_1;

    protected $name = self::TABLE_NAME;

    //积分 提现 比率
    const POINTS_RATE =1; //  积分 /金额
    public static function addRecord($user_id,$amount,$account)
    {
        return self::commonQuery(self::TABLE_NAME)
            ->insert([
                'record_user_id'=>$user_id,
                'record_amount'=>$amount,
                'record_account'=>$account,
                'record_time'=>time()
            ],false,true);
    }

    //提现 扣除 用户积分 和添加 积分记录
    public static function handleWithDraw($user_id,$amount,$account)
    {
        Db::startTrans();

        $points = $amount * self::POINTS_RATE;
        try{
            $user_points = User::getUserPointsForUpdate($user_id);
            if($user_points < $points)
            {
                Db::rollback();
                return ['status'=>false,'msg'=>'积分不足'];
            }
            User::descUserPoints($user_id,$points);
            $record_id = self::addRecord($user_id,$amount,$account);
            PointsRecord::addRecord($user_id,PointsRecord::POINTS_WITHDRAW,$record_id,$points);
        }catch (\Exception $e)
        {
            Db::rollback();
            return false;
        }
        Db::commit();
        return ['status'=>true,'msg'=>'','record_id'=>$record_id];
    }
    public static function getNotifyParam($record_id)
    {
        return ['module'=>USER_MODULE,'module_id'=>$record_id,
            'notify_type'=>AdminNotify::USER_WITHDRAW,
        ];
    }
}